﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text.RegularExpressions;
using GMS.BLL;
using GMS.Model;
using GMS.Utils;
using Maticsoft.DBUtility;

public partial class Public_ModuleManager : System.Web.UI.Page
{
    SysFunModuleBLL bll = new SysFunModuleBLL();
    SysFunModuleAccessBLL accessbll = new SysFunModuleAccessBLL();
    SysFunModuleOraBLL orabll = new SysFunModuleOraBLL();
    SysFunModule model = new SysFunModule();
    private DbHelper db = new DbHelper();

    string userid;
    const string NODETARGET = "ContFrame";

    protected void Page_Load(object sender, EventArgs e)
    {
        //if (Session["UserID"] == null)
        //{
        //    Response.Write("<script>alert('登陆已过期，请重新登陆！');top.location.href='../../Login.aspx';</script>");
        //    return;
        //}
        //userid = Session["UserID"].ToString();
        if (!IsPostBack)
        {
            Button_Delete.Enabled = false;
            Button_Update.Enabled = false;
            LoadMenu(TreeViewModule.Nodes, null,"");
            detailDiv.Attributes.Add("onload", "SetLocation(this)");
        }
        detailDiv.Visible = false;
        this.Button_Insert.Visible = false;
        this.Button_Delete.Visible = false;
        this.Button_Update.Visible = false;
        this.TextBox_Url.Attributes.Add("readonly","readonly"); 
        SetAccessRight();
        BindDrpTab();
    }

    public void BindDrpTab()
    {
        string strSql = "select tabname,tabcode from tab_tabinfo order by tabname";
        //HELM
        DataSet ds = db.Query(strSql);
        DDLCommonPageTab.DataValueField = "tabcode"; //值为表编码
        DDLCommonPageTab.DataTextField = "tabname";  //显示的文本为表名
        DDLCommonPageTab.DataSource = ds;
        DDLCommonPageTab.DataBind();
        DDLCommonPageTab.Items.Insert(0, new ListItem("", ""));//插入空项，此举必须放到数据绑定之后
    }

    public void BindDrpClass(string selectedValue)
    {
        DataTable dt = null;
        if ((int)EnumHelper.E_DbType.DB_ACCESS == PubConstant.GetDBType())
        {
            dt = accessbll.GetAllList();
        }
        else if ((int)EnumHelper.E_DbType.DB_SQL == PubConstant.GetDBType())
        {
            dt = bll.GetAllList();
        }
        else if ((int)EnumHelper.E_DbType.DB_ORACLE == PubConstant.GetDBType())
        {
            dt = orabll.GetAllList();
        }
        else
            return; 

        DropDownListFather.Items.Clear();
        DropDownListFather.Items.Add(new ListItem("选择父模块...", ""));
        DataRow[] drs = dt.Select("FATHERMODULEID is null ");

        foreach (DataRow dr in drs)
        {
            ListItem item = new ListItem();

            string id = dr["TABSYSID"].ToString();
            string classname = dr["MODULENAME"].ToString();

            //顶级分类显示形式
            //item.Attributes.Add("title", classname);
            classname = "╋" + classname;

            item.Text = classname;
            item.Value = id;
            if (id == selectedValue)
                item.Selected = true;

            DropDownListFather.Items.Add(item);
            int sonparentid = int.Parse(id);
            string blank = "　　";
            //递归子分类方法
            BindNode(sonparentid, dt, blank,selectedValue);
        }
        DropDownListFather.DataBind();
    }

    private void BindNode(int parentid, DataTable dt, string blank, string selectedValue)
    {
        DataRow[] drs = dt.Select("FATHERMODULEID= " + parentid);

        foreach (DataRow dr in drs)
        {
            string id = dr["TABSYSID"].ToString();
            string classname = dr["MODULENAME"].ToString();

            classname = blank + classname;

            ListItem item = new ListItem();
            item.Text = classname;
            item.Value = id;
            if (id == selectedValue)
                item.Selected = true;
            DropDownListFather.Items.Add(item);

            int sonparentid = int.Parse(id);
            string blank2 = blank + "　　";

            BindNode(sonparentid, dt, blank2, selectedValue);
        }
    }

    public void LoadMenu(TreeNodeCollection nodes, int? intParentID,string search)
    {
        DataTable modelDt = null;
        if ((int)EnumHelper.E_DbType.DB_ACCESS == PubConstant.GetDBType())
        {            
            modelDt = accessbll.GetList("");
        }
        else if ((int)EnumHelper.E_DbType.DB_SQL == PubConstant.GetDBType())
        {        
            modelDt = bll.GetList("");
        }
        else if ((int)EnumHelper.E_DbType.DB_ORACLE == PubConstant.GetDBType())
        {
            modelDt = orabll.GetList("");
        }
        else
            return; 

        String strExpression = String.Empty;
        if (intParentID == null)
            strExpression = "FATHERMODULEID is null";
        else
            strExpression = "FATHERMODULEID =" + intParentID;

        DataRow[] dr = modelDt.Select(strExpression);
        for (int i = 0; i < dr.Length; i++)
        {
            //新建一个节点
            TreeNode tn = new TreeNode();
            tn.Text = dr[i]["MODULENAME"].ToString() + " [" + dr[i]["MODULESEQ"].ToString() + "]";
            tn.Value = dr[i]["TABSYSID"].ToString();
            tn.SelectAction = TreeNodeSelectAction.Select;
            
            nodes.Add(tn);
            if (search != "" && tn.Text.Contains(search))
            {
                tn.Text = tn.Text.Replace(search,"<span style='background-color:yellow'>" + search + "</span>");
                TreeNode tmpParent = tn.Parent;
                while (tmpParent != null)
                {
                    tmpParent.Expanded = true;
                    tmpParent = tmpParent.Parent;
                }
            }else
            {
                if (dr[i]["ISUNFOLD"].ToString() == "0")
                    tn.Expanded = false;
                else
                    tn.Expanded = true;
            }
            LoadMenu(tn.ChildNodes, Convert.ToInt32(tn.Value), search);
        }
    }

    //选择树内项目显示内容
    protected void TreeViewModule_SelectedNodeChanged(object sender, EventArgs e)
    {
        detailDiv.Visible = true;
        ClientScriptManager script = Page.ClientScript;
        script.RegisterStartupScript(this.GetType(),"LocateDiv", "SetDetailDivXY('" + Request.Form["eventX"] + "','" + Request.Form["eventY"] + "');",true);
        BindDrpClass("");
        //设置dropdownlist选中值
        if (TreeViewModule.SelectedNode.Parent != null)
        {
            DropDownListFather.SelectedIndex = DropDownListFather.Items.IndexOf(DropDownListFather.Items.FindByValue(TreeViewModule.SelectedNode.Parent.Value));
        }
        else
        {
            DropDownListFather.SelectedIndex = -1;
        }

        SysFunModule model = null;
        if ((int)EnumHelper.E_DbType.DB_ACCESS == PubConstant.GetDBType())
        {
            model = accessbll.GetModel(Convert.ToInt32(TreeViewModule.SelectedValue));
        }
        else if ((int)EnumHelper.E_DbType.DB_SQL == PubConstant.GetDBType())
        {
            model = bll.GetModel(Convert.ToInt32(TreeViewModule.SelectedValue));
        }
        else if ((int)EnumHelper.E_DbType.DB_ORACLE == PubConstant.GetDBType())
        {
            model = orabll.GetModel(Convert.ToInt32(TreeViewModule.SelectedValue));
        }
        else
            return; 

        ModuleId.Value = model.TABSYSID.ToString();
        TextBox_ModuleName.Text = model.MODULENAME;
        TextBox_ModuleSeq.Text = model.MODULESEQ.ToString();
        DDLIsUnFold.SelectedIndex = DDLIsUnFold.Items.IndexOf(DDLIsUnFold.Items.FindByValue(model.ISUNFOLD.ToString()));
        TextBox_Url.Text = model.URL;
        Button_Delete.Enabled = true;
        Button_Update.Enabled = true;

    }

    //删除
    protected void Button_Delete_Click(object sender, EventArgs e)
    {
        try
        {
            //bll.Delete(ModuleId.Value);
            if ((int)EnumHelper.E_DbType.DB_ACCESS == PubConstant.GetDBType())
            {
                accessbll.Delete(ModuleId.Value);
            }
            else if ((int)EnumHelper.E_DbType.DB_SQL == PubConstant.GetDBType())
            {
                bll.Delete(ModuleId.Value);
            }
            else if ((int)EnumHelper.E_DbType.DB_ORACLE == PubConstant.GetDBType())
            {
                orabll.Delete(ModuleId.Value);
            }
            else
                return; 

            ToAlert("删除成功！");

            //更新Application中的模块信息，以便下次登录或者刷新左侧树可以显示最新的模块信息
            GMS.Web.AppOperation.ApplicationOperation.SetUserModuleList(1, null);

            //BindDrpClass(DropDownListFather.SelectedValue);
            detailDiv.Visible = false;
            TreeViewModule.Nodes.Clear();
            LoadMenu(TreeViewModule.Nodes, null, "");
         
        }
        catch (ArgumentException ae)
        {
            ToAlert("删除失败！" + ae.Message);
        }
    }

    //插入
    protected void Button_Insert_Click(object sender, EventArgs e)
    {
        try
        {
            if ((int)EnumHelper.E_DbType.DB_ACCESS == PubConstant.GetDBType())
            {
                accessbll.Add(userid, DDLIsUnFold.SelectedValue, TextBox_ModuleName.Text.Trim(), TextBox_ModuleSeq.Text, TextBox_Url.Text, DropDownListFather.SelectedValue);
            }
            else if ((int)EnumHelper.E_DbType.DB_SQL == PubConstant.GetDBType())
            {
                bll.Add(userid, DDLIsUnFold.SelectedValue, TextBox_ModuleName.Text.Trim(), TextBox_ModuleSeq.Text, TextBox_Url.Text, DropDownListFather.SelectedValue);
            }
            else if ((int)EnumHelper.E_DbType.DB_ORACLE == PubConstant.GetDBType())
            {
                orabll.Add(userid, DDLIsUnFold.SelectedValue, TextBox_ModuleName.Text.Trim(), TextBox_ModuleSeq.Text, TextBox_Url.Text, DropDownListFather.SelectedValue);
            }
            else
                return; 
           
            ToAlert("新增成功！要想看到此新增模块，请到角色管理中添加此模块的权限！");

            //更新Application中的模块信息，以便下次登录或者刷新左侧树可以显示最新的模块信息
            GMS.Web.AppOperation.ApplicationOperation.SetUserModuleList(1, null);

            //BindDrpClass(DropDownListFather.SelectedValue);
            detailDiv.Visible = false;
            TreeViewModule.Nodes.Clear();
            LoadMenu(TreeViewModule.Nodes, null, "");
        }
        catch (ArgumentException ae)
        {
            ToAlert("新增失败！" + ae.Message);
        }

    }

    //更新
    protected void ButtonUpdate_Click(object sender, EventArgs e)
    {
        try
        {
            this.TextBox_Url.Enabled = true;
            if ((int)EnumHelper.E_DbType.DB_ACCESS == PubConstant.GetDBType())
            {
                accessbll.Update(ModuleId.Value, userid, DDLIsUnFold.SelectedValue, TextBox_ModuleName.Text.Trim(), TextBox_ModuleSeq.Text, TextBox_Url.Text, DropDownListFather.SelectedValue);
            }
            else if ((int)EnumHelper.E_DbType.DB_SQL == PubConstant.GetDBType())
            {
                bll.Update(ModuleId.Value, userid, DDLIsUnFold.SelectedValue, TextBox_ModuleName.Text.Trim(), TextBox_ModuleSeq.Text, TextBox_Url.Text, DropDownListFather.SelectedValue);
            }
            else if ((int)EnumHelper.E_DbType.DB_ORACLE == PubConstant.GetDBType())
            {
                orabll.Update(ModuleId.Value, userid, DDLIsUnFold.SelectedValue, TextBox_ModuleName.Text.Trim(), TextBox_ModuleSeq.Text, TextBox_Url.Text, DropDownListFather.SelectedValue);
            }
            else
                return; 
            
            ToAlert("更新成功！");

            //更新Application中的模块信息，以便下次登录或者刷新左侧树可以显示最新的模块信息
            GMS.Web.AppOperation.ApplicationOperation.SetUserModuleList(1, null);

            //BindDrpClass(DropDownListFather.SelectedValue);
            detailDiv.Visible = false;
            TreeViewModule.Nodes.Clear();
            LoadMenu(TreeViewModule.Nodes, null,"");
        }
        catch(ArgumentException ae)
        {
            ToAlert("更新失败！"+ae.Message);
        }
    }

    //查询
    protected void Query_ServerClick(object sender, EventArgs e)
    {
        string search = QryText.Value;
        TreeViewModule.Nodes.Clear();
        LoadMenu(TreeViewModule.Nodes, null, search);
    }
    protected void Button_Cancel_Click(object sender, EventArgs e)
    {
        detailDiv.Visible = false;
    }
    public void ToAlert(string txt)
    {
        this.Page.RegisterStartupScript("onload", "<script>alert('" + txt + "');</script>");
    }

    private void DoRight(GMS.Model.User user, int TabSysID)
    {
        int[] right = RoleModuleRightOper.GetRoleModuleRightInt(user, TabSysID);

        foreach (int i in right)
        {
            switch (i)
            {
                case (int)EnumHelper.E_Right.R_SEARCH:
                    //BtnCustomSearch.Visible = true;
                    break;
                case (int)EnumHelper.E_Right.R_INSERT:
                    this.Button_Insert.Visible = true;
                    break;
                case (int)EnumHelper.E_Right.R_UPDATE:
                    this.Button_Update.Visible = true;
                    break;
                case (int)EnumHelper.E_Right.R_DELETE:
                    this.Button_Delete.Visible = true;
                    break;
                default:
                    break;
            }
        }
    }

    private void SetAccessRight()
    {
        GMS.Model.User user = (GMS.Model.User)Session["_User"];
        if (user == null)
        {
            Response.Write("<script>alert('登陆已过期，请重新登陆！');top.location.href='" + Request.ApplicationPath + "/Login.aspx';</script>");
            return;
        }
                
        int TabSysID; //模块ID
        if (Request.Params["TabSysID"] != null)
        {
            TabSysID = Int32.Parse(Request.Params["TabSysID"]);
            if (Session["TabSysID"] == null)
            {
                Session.Add("TabSysID", TabSysID);
            }
            else
            {
                Session["TabSysID"] = TabSysID;
            }

            DoRight(user, TabSysID);  
        }
        else if (Session["TabSysID"] != null)
        {
            DoRight(user, Int32.Parse(Session["TabSysID"].ToString()));
        }
        else
        {
            this.Button_Insert.Visible = true;
            this.Button_Delete.Visible = true;
            this.Button_Update.Visible = true;
        }

    }

}
